<template>
  <view class="content">
    <view class="top-block pt-20 pb-20">
      <view class="search-block pl-20 pr-20">
        <u-search placeholder="请输入作业名称" v-model="params.name" action-text="筛选" :action-style="{color: '#3F99F7', fontWeight: '500'}" @focus="closeModel" @custom="openPopup" @search="submit()"></u-search>
      </view>
      <view class="check-block pt-20 pl-20 pr-20">
        <view class="check-item">申请单位：{{params.applicationUnit ? params.applicationUnit : '---'}}</view>
        <view class="check-item">申请人：{{params.applicant ? params.applicant : '---'}}</view>
        <view class="check-item">作业类型：{{type ? type : '---'}}</view>
        <view class="check-item" style="width: 40%;">作业日期：{{params.startTime ? params.startTime : '---'}} 至 {{params.endTime ? params.endTime : '---'}}</view>
      </view>
    </view>
    <view class="body-block">
      <view class="left-block">
        <scroll-view scroll-y="true" class="scroll-Y" :style="'width: 100%; height: '+ (pageHeight - 80) +'px;'" :scroll-top="0">
          <view :class="index == activeIndex ? 'item-block-active' : 'item-block'" v-for="(item, index) in stateList" :key="index" @click="changeType(item.status, index)">{{item.name}}</view>
        </scroll-view>
      </view>
      <view class="right-block">
        <scroll-view scroll-y="true" class="scroll-Y" :style="'width: 100%; height: '+ (pageHeight - 80) +'px;'" :scroll-top="0">
          <view v-if="JSON.stringify(list) != '[]'" class="list-block pl-20 pr-20">
            <view class="item-block pd-20 mt-20" v-for="(item, index) in list" :key="index">
              <view class="item-title">{{item.name ? item.name : '-'}}</view>
              <view class="item-info">类型：{{item.type != null ? typeList[item.type] : '-'}}</view>
              <view class="item-info">编号：{{item.number ? item.number : '-'}}</view>
              <view class="item-info">申请人：{{item.applicant ? item.applicant : '-'}}</view>
              <view class="item-info">创建时间：{{item.createTime ? item.createTime : '-'}}</view>
              <view class="button-block mt-10">
                <view v-if="params.status == 1" class="button-success" @click="checkItem(item.type, item.id, 'update')">修改</view>
                <view v-if="params.status == 1" class="button" @click="submitWorkInfo(item.id)">提交审核</view>
                <view v-if="params.status == 3 && (item.type == '1' || item.type == '2')" class="button-success" @click="checkItem(item.type, item.id, 'push')">追加</view>
                <!-- <view v-if="params.status == 3 && item.type == '2'" class="button-success" @click="checkItem(item.type, item.id, 'push')">追加</view> -->
                <view v-if="params.status == 2 || params.status == 3 || params.status == 4 || params.status == 5" class="button" @click="checkItem(item.type, item.id, 'detail')">查看</view>
                <view v-if="params.status == 3 || params.status == 5" class="button-warning" @click="routeToPDF(item.id)">预览PDF</view>
                <!-- <view v-if="params.status == 3" class="button-danger" @click="finishItem(item.id)">结束</view> -->
              </view>
            </view>
            <u-divider v-if="pushState" textSize="24rpx" text="加载更多" @click="getMoreData"></u-divider>
            <u-divider v-else textSize="24rpx" text="没有更多数据了"></u-divider>
          </view>
          <view v-else style="padding-top: 300rpx;">
            <u-empty text="暂无数据" mode="data" icon-size="60"></u-empty>
          </view>
        </scroll-view>
      </view>
    </view>
    <u-popup :show="popupState" mode="top" :closeOnClickOverlay="true" :customStyle="{marginTop: '140rpx'}" @close="closePopup">
      <view class="popup-block pd-20">
        <view class="popup-item pt-20 pb-20 border-b-common">
          <view class="item-label">申请单位</view>
          <view class="item-select">
            <input class="input text-r mr-10" v-model="params.applicationUnit" placeholder="请输入申请单位" placeholder-class="placeholder" @click="closeModel" />
          </view>
        </view>
        <!-- <view class="popup-item pt-20 pb-20 border-b-common">
          <view class="item-label">申请单位</view>
          <view class="item-select" @click="routeByUrl('/pagesCommon/departmentList?paramsKey=check')">
            <text v-if="params.applicationUnit" class="mr-10">{{params.applicationUnit}}</text>
            <text v-else class="item-default-text mr-10">请选择检查单位</text>
            <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
          </view>
        </view> -->

        <view class="popup-item pt-20 pb-20 border-b-common">
          <view class="item-label">申请人</view>
          <view class="item-select">
            <input class="input text-r mr-10" v-model="params.applicant" placeholder="请输入申请人" placeholder-class="placeholder" @click="closeModel" />
          </view>
        </view>
        <view class="popup-item pt-20 pb-20 border-b-common">
          <view class="item-label">作业类型</view>
          <view class="item-select" @click="openPicker()">
            <text v-if="type" class="mr-10">{{type}}</text>
            <text v-else class="item-default-text mr-10">请选择作业类型</text>
            <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
          </view>
        </view>
        <view class="popup-item pt-20 pb-20 border-b-common">
          <view class="item-label">作业日期</view>
          <view class="item-select" @click="openCalendar()">
            <text v-if="params.startTime && params.endTime" class="mr-10">{{params.startTime ? params.startTime : '---'}} 至 {{params.endTime ? params.endTime : '---'}}</text>
            <text v-else class="item-default-text mr-10">请选择作业日期</text>
            <u-icon name="calendar" size="46rpx" color="#3F99F7"></u-icon>
          </view>
        </view>
        <view class="button-block pt-20">
          <u-button type="info" text="重置" :custom-style="{width: '340rpx', backgroundColor: '#FFFFFF !important'}" @click="resetForm()"></u-button>
          <u-button type="primary" text="确认" :custom-style="{width: '340rpx'}" @click="submit()"></u-button>
        </view>
      </view>
    </u-popup>
    <u-calendar :show="calendarState" :minDate="minDate" :maxDate="maxDate" :defaultDate="defaultDate" :allowSameDay="true" :monthNum="36" mode="range" color="#3F99F7" :closeOnClickOverlay="true" @confirm="calendarConfirm" @close="calendarClose"></u-calendar>
    <u-picker :show="pickerState" :columns="pickerList" keyName="label" @confirm="pickerConfirm" @cancel="pickerCancel"></u-picker>
  </view>
</template>

<script>
  import { getWorkOrderListApi, submitWorkInfoApi, getWorkDetailApi } from '@/apis/work/index.js'
  import { getDictListApi } from '@/apis/work/common.js'
  import dayjs from 'dayjs'

  export default {
    data() {
      return {
        pageHeight: uni.getSystemInfoSync().windowHeight,
        minDate: dayjs().subtract(1, 'year').format('YYYY-MM-DD'),
        maxDate: dayjs().add(1, 'year').format('YYYY-MM-DD'),
        defaultDate: [dayjs().subtract(1, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
        calendarState: false,
        popupState: false,
        pickerState: false,
        params: {
          name: '',
          applicant: '',
          type: '',
          startTime: '',
          endTime: '',
          status: 1,
          pageNo: 1,
          pageSize: 10
        },
        stateList: [
          { name: '待提交', status: 1 },
          { name: '审批中', status: 2 },
          { name: '作业中', status: 3 },
          { name: '已驳回', status: 4 },
          { name: '已完工', status: 5 }
        ],
        typeList: {},
        list: [],
        pushState: true,
        activeIndex: 0,
        pickerList: [],
        type: ''
      }
    },
    onLoad() {
      this.getWorkTypeList()
    },
    onShow() {
      this.getWorkOrderList(Object.assign(this.params, {pageNo: 1}))
    },
    methods: {
      submit: function() {
        let params = JSON.parse(JSON.stringify(this.params))
        if(params.startTime) Object.assign(params, { startTime: `${params.startTime} 00:00:00`})
        if(params.endTime) Object.assign(params, { endTime: `${params.endTime} 23:59:59`})
        Object.assign(params, { pageNo: 1})
        this.getWorkOrderList(params)
      },
      resetForm: function() {
        this.params.applicationUnit = ''
        this.type = ''
        Object.assign(this.params, { name: '', applicant: '', type: '', applicationUnit: '', startTime: '', endTime: '', pageNo: 1})
        this.getWorkOrderList(this.params)
      },
      getWorkTypeList: function() {
        getDictListApi('licence_type').then(res => {
          let typeList = {}
          if(res.length > 0) res.map(item => Object.assign(typeList, { [item.value]: item.label }))
          this.typeList = typeList
          this.pickerList = [res]
        }).catch(err => console.warn(err))
      },
      getWorkOrderList: function(params, freshState = true) {
        getWorkOrderListApi(params).then(res => {
          if(freshState) {
            this.pushState = true
            this.list = res.list
          } else {
            this.list = this.list.concat(res.list)
          }
          if(res.list.length < this.params.pageSize) this.pushState = false
          this.popupState = false
        }).catch(err => console.warn(err))
      },
      submitWorkInfo: function(id) {
        submitWorkInfoApi({licenceId: id}).then(res => {
          uni.showToast({ title: '提交成功', icon: 'none' })
          this.getWorkOrderList(Object.assign(this.params, {pageNo: 1}))
        }).catch(err => console.warn(err))
      },
      getMoreData: function() {
        this.getWorkOrderList(Object.assign(this.params, {pageNo: this.params.pageNo + 1}), false)
      },
      changeType: function(status, index) {
        if(index == this.activeIndex) return false
        this.activeIndex = index
        let params = JSON.parse(JSON.stringify(this.params))
        if(params.startTime) Object.assign(params, { startTime: `${params.startTime} 00:00:00`})
        if(params.endTime) Object.assign(params, { endTime: `${params.endTime} 23:59:59`})
        Object.assign(params, { status, pageNo: 1 })
        this.params.status = status
        this.getWorkOrderList(params)
      },
      checkItem: function(type, id, serviceType) {
        if (type == '1') {
          uni.navigateTo({ url: `/pagesWork/workCreateHot?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '2') {
          uni.navigateTo({ url: `/pagesWork/workCreateSpace?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '3') {
          uni.navigateTo({ url: `/pagesWork/workCreateBlindPlate?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '4') {
          uni.navigateTo({ url: `/pagesWork/workCreateHigh?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '5') {
          uni.navigateTo({ url: `/pagesWork/workCreateHoisting?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '6') {
          uni.navigateTo({ url: `/pagesWork/workCreateElectric?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '7') {
          uni.navigateTo({ url: `/pagesWork/workCreateDigging?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else if (type == '8') {
          uni.navigateTo({ url: `/pagesWork/workCreateRoad?type=${type}&id=${id}&serviceType=${serviceType}` })
        } else {
          uni.showToast({ title: `未找到${this.activeName}作业页面`, icon: 'none' })
        }
      },
      routeToPDF: function(id) {
        getWorkDetailApi({ id }).then(res => {
          let url = res.pdfUrl
          uni.downloadFile({
            url: res.pdfUrl,
            success: res => {
              uni.openDocument({
                filePath: res.tempFilePath,
                showMenu: true,
                fail: () => uni.showToast({  title: '文件打开失败', icon: 'none' })
              })
            },
            fail: () => uni.showToast({  title: '本地文件下载失败', icon: 'none' })
          })
          // uni.navigateTo({ url: `/pagesCommon/webviewPDF?url=${encodeURIComponent(url)}` })
        }).catch(err => console.warn(err))
      },
      openPopup: function() {
        this.calendarState = false
        this.pickerState = false
        this.popupState = !this.popupState
      },
      closePopup: function() {
        this.popupState = false
      },
      closeModel: function() {
        this.calendarState = false
        this.pickerState = false
      },
      openPicker: function() {
        this.calendarState = false
        this.pickerState = true
      },
      openCalendar: function() {
        this.pickerState = false
        this.calendarState = true
      },
      pickerConfirm: function(event) {
        this.params.type = event.value[0].value
        this.type = event.value[0].label
        this.pickerState = false
      },
      pickerCancel: function() {
        this.pickerState = false
      },
      calendarConfirm: function(event) {
        this.params.startTime = event[0]
        this.params.endTime = event[event.length - 1]
        this.calendarState = false
      },
      calendarClose: function() {
        this.calendarState = false
      },
      routeByUrl: function(url) {
        uni.navigateTo({ url })
      }
    }
  }
</script>

<style>
  page {
    background-color: #F4F4F4;
  }
</style>

<style lang="scss" scoped>
  .border-b-common {
    border-bottom: 1rpx solid #F4F4F4;
  }
  .content {
    padding-top: 160rpx;
    .top-block {
      width: 100%;
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background-color: #FFFFFF;
      overflow: hidden;
      border-bottom-left-radius: 20rpx;
      border-bottom-right-radius: 20rpx;
      box-shadow: 0 0 10rpx 0 #F4F4F4;
      z-index: 11111;
      .check-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .check-item {
          width: 30%;
          font-size: 24rpx;
          line-height: 32rpx;
          color: #3F99F7;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .body-block {
      display: flex;
      .left-block {
        width: 30%;
        background-color: #FFFFFF;
        box-shadow: 0 0 10rpx 0 #F4F4F4;
        .item-block {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 30rpx;
          color: #333333;
          height: 80rpx;
        }
        .item-block-active {
          @extend .item-block;
          color: #3F99F7;
          background-color: #EFEFEF;
        }
      }
      .right-block {
        width: 70%;
        .list-block {
          .item-block {
            background-color: #FFFFFF;
            border-radius: 10rpx;
            box-shadow: 0 0 10rpx 0 #F4F4F4;
            .item-title {
              font-size: 30rpx;
              line-height: 44rpx;
              font-weight: 500;
              color: #333333;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .item-info {
              font-size: 26rpx;
              line-height: 36rpx;
              color: #999999;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              margin-top: 5rpx;
            }
            .button-block {
              display: flex;
              align-items: center;
              justify-content: flex-end;
              .button {
                height: 46rpx;
                line-height: 46rpx;
                border-radius: 30rpx;
                padding: 0 15rpx;
                font-size: 24rpx;
                color: #3F99F7;
                background-color: #FFFFFF;
                border: 1rpx solid #3F99F7;
                margin-left: 20rpx;
              }
              .button-success {
                @extend .button;
                color: #19BE6B;
                border-color: #19BE6B;
              }
              .button-warning {
                @extend .button;
                color: #FF9900;
                border-color: #FF9900;
              }
              .button-danger {
                @extend .button;
                color: #FA3534;
                border-color: #FA3534;
              }
              .button:first-child {
                margin-left: 0;
              }
            }
          }
        }
      }
    }
    .popup-block {
      .popup-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item-label {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
        }
        .item-select {
          display: flex;
          align-items: center;
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
          .item-default-text {
            color: #999999;
          }
        }
      }
      .button-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
    }
  }
</style>
